# coding=UTF-8


import cgi
import wsgiref.handlers

import sys,os
from model.article import Article
from model.comment import Comment
from model.tag import Tag
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
import string
import util
from util import PageInfo
import datetime
import logging
logging.logMultiprocessing = 0


def addTagCount(tagName):
  tag = Tag.gql('where name =:1',tagName).get()
  if tag!=None:
    tag.count+=1
  else:
    tag= Tag()
    tag.name=tagName
    tag.count=1
  tag.put()

def subTagCount(tagName):
  tag = Tag.gql('where name =:1',tagName).get()
  if tag==None:
    return
  tag.count-=1
  tag.put()

class MainPage(webapp.RequestHandler):
  def get(self):
    articles_query = Article.all().order('-date')
    articles = articles_query.fetch(2)
    template_values = {
      'articles': articles
    }
    util.render('view/index.html',template_values,self)



class ArticleList(webapp.RequestHandler):
  pageSize=10
  def get(self):
    articles_query = Article.all().order('-date')
    pageInfo = PageInfo(articles_query.count(),self.request.get('pageNo'),self.pageSize)
    articles=articles_query.fetch(pageInfo.pageSize,pageInfo.startOffset())
    pageCount= int(articles_query.count()/self.pageSize)+1
    template_values = {
      'articles': articles,
      'pageInfo':  pageInfo
    }
    util.render('view/articleList.html',template_values,self)

class ViewArticle(webapp.RequestHandler):
  def get(self):
    keyStr = self.request.get('key')
    article = db.get(db.Key(keyStr))
    template_values = {
      'article': article
    }
    util.render('view/viewArticle.html',template_values,self)

class AddArticle(webapp.RequestHandler):
  def post(self):
    if not users.is_current_user_admin():
      util.render('view/errorPage.html',{'errorMsg' : "没有权限"},self)
      return
    article = getAnArticle(self.request.get('key'))
    if article==None:
      article=Article()
    else:
      for tag in article.tags:
        subTagCount(tag)
    article.tags=[]
    for tag in self.request.get('tags').split(' '):
      if tag !='':
        article.tags.append(tag)
        addTagCount(tag)
    article.content = self.request.get('content')
    article.title = self.request.get('title')
    article.put()
    self.redirect('/')
        
class ComposeArticle(webapp.RequestHandler):
  def get(self):
    if not (users.is_current_user_admin() or (users.get_current_user() and users.get_current_user().email()=='shadowzqj@gmail.com')):
      util.render('view/errorPage.html',{'errorMsg' : "没有权限"},self)
      return
    template_values={}
    template_values['article']=getAnArticle(self.request.get('key'))
    util.render('view/compose.html',template_values,self)

def getAnArticle(keyStr):
  article=None
  if keyStr!=None and keyStr!="":
    article = db.get(db.Key(keyStr))
  return article

    
class Archive(webapp.RequestHandler):
  def get(self):
    month=string.atoi(self.request.get('month'))
    year=string.atoi(self.request.get('year'))
    fromDay=datetime.datetime(year,month,1)
    month+=1
    if month==13:
      year+=1
      month=1
    toDay=datetime.datetime(year,month,1)
    articles_query=Article.gql('where date >= :1 and date<:2',fromDay,toDay)
    util.render('view/archive.html',
        {'articles':articles_query.fetch(1000),
        'fromDay':fromDay,
        'toDay':toDay
        },self)

class TagArticle(webapp.RequestHandler):
  pageSize=10
  def get(self):
    tagName=self.request.get('tag')
    articles_query = Article.gql('where tags=:1',tagName)
    pageInfo = PageInfo(articles_query.count(),self.request.get('pageNo'),self.pageSize)
    articles=articles_query.fetch(pageInfo.pageSize,pageInfo.startOffset())
    pageCount= int(articles_query.count()/self.pageSize)+1
    template_values = {
      'articles': articles,
      'pageInfo':  pageInfo,
      'tag':tagName
    }
    util.render('view/tagArticleList.html',template_values,self)

class Album(webapp.RequestHandler):
  def get(self):
    util.render('view/album.html',{},self)
    

def main():
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/addArticle', AddArticle),
                                       ('/compose',ComposeArticle),
                                       ('/viewArticle',ViewArticle),
                                       ('/articleList',ArticleList),
                                       ('/archive',Archive),
                                       ('/tag',TagArticle),
                                       ('/album',Album)
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
